#include <unistd.h>
#include <wait.h>
#include <iostream>
#include <string.h>
#include <stdlib.h>

int tokenize_it(char *, char **);
int cd(char *);

using namespace std;


void handleInt(int a) {
    cout << "nooooooo" << endl;
}


void initSignals() {
    signal(SIGINT, handleInt);
}



int main(int argc, char** argv)
{
    char cmd_buffer[512],*tokens[20];
    int pid,status,is_bg=0,i;
    char newline_off;
    bool running = true;

    initSignals();
    cout << ": ";
    while (running) //prompt ausgeben und Kommando lesen
    {
        cin.get(cmd_buffer,512);
	//istream is(cmd_buffer);
        
        if (!*cmd_buffer || (cmd_buffer[0] == ' ')) //nichts eingegeben?
        {
            cin.clear();
	    cin.ignore(512, '\n'); 
	    cout << ": ";
            continue;
        }
	//newline aus Puffer
        cin.get(newline_off);

        if (cmd_buffer[i=strlen(cmd_buffer)-1] =='&') //Kommando im Hintergrund ausführen?
        {
            cmd_buffer[i]=0;
            is_bg = 1;
        } else
        {
            is_bg = 0;
        }

        tokenize_it(cmd_buffer,tokens);

        // Kommando in syntaktische Teile zerpflücken

        if (!strcmp(*tokens,"cd"))
        {
            cd(*(tokens+1));
        } else if (!strcmp(*tokens,"exit"))
        {
            running = false;
            return 0;
        }  // interne Kommandos ?
        else
        {
            if (!(pid = fork()))//Kindsprozeß erzeugen
            {
                cout << *tokens << " | " << tokens << endl;
                if (execvp(*tokens,tokens)==-1) {
                    cout << "Fehler" << endl;
                    return 1;
                } else {
                    cout << "Irgenwas" << endl;
                }
                cout << "ende start" << endl;
            } else
            {
                if (!is_bg)
                {
                    while (wait(&status)!=pid);
                }

                //auf das Ende warten
                else
                {
                    cout << "....started with " << pid << endl;
                }
            }
        }
        cout << ": ";
    }
    cout << "Endegelände" << endl;
}

int tokenize_it(char *cmd, char **tab)
{
    while (*tab++=strtok(cmd," \t"))
    {
        //liefert Zeiger auf tokens
        cmd=0;
    }
}

int cd(char *path)
{
    if (path == 0)
    {
        return chdir(getenv("HOME"));
    }
    cout << path << endl;
    return chdir(path);
}

